package com.etool.action.curd;


import java.io.IOException;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;

import com.etool.modules.curd.model.Column;
import com.etool.modules.curd.service.CurdService;
import com.etool.modules.curd.util.CurdConfigUtil;
import com.opensymphony.xwork2.ActionSupport;
public class CreateAction extends ActionSupport{
	
	private HttpServletResponse response=ServletActionContext.getResponse();
	private HttpServletRequest request=ServletActionContext.getRequest();
	private String target;

	private CurdService curdService;

	
	

	@Action(value="create")
	public String create()
	{
		try
		{
		CurdConfigUtil.setSecondJdbc(curdService, target);
		
		List<Column> cols=curdService.desc(target);
		
		Map<String, Object> params=new HashMap<String, Object>();
		
		for(Column item:cols)
		{
			if(item.isAuto_increment() && (StringUtils.isEmpty(request.getParameter(item.getName())) || StringUtils.equals("null",request.getParameter(item.getName()))))
			{
				continue;
			}
			params.put(item.getName(), request.getParameter(item.getName()));
		}
		
		curdService.create(target, params);
		CurdConfigUtil.disableSecondJdbc(curdService);
		
		response.setContentType("text/html;charset=utf-8");
		response.getWriter().write(JSONObject.fromObject(Collections.singletonMap("success", true)).toString());
		response.getWriter().flush();
		}catch(Exception e)
		{
			response.setContentType("text/html;charset=utf-8");
			
			try {
				response.getWriter().write(JSONObject.fromObject(Collections.singletonMap("errorMsg", e.getMessage())).toString());
				response.getWriter().flush();
			} catch (IOException e1) {
				e1.printStackTrace();
			}
			
		}
		
		
		
		return NONE;
	}
	
	public String getTarget() {
		return target;
	}

	public void setTarget(String target) {
		this.target = target;
	}
	

	
	public CurdService getCurdService() {
		return curdService;
	}

	public void setCurdService(CurdService curdService) {
		this.curdService = curdService;
	}



}
